import React, { PureComponent } from 'react';
import cx from 'classnames';
import Search from './search';
import styles from './styles.m.less';
import fangg from './fangg.json';

export default class CountryCodeList extends PureComponent {
    state = {
        action: 'show', // 主件动作展示，默认进入
        inputValue: '',
    };

    componentDidMount() {
        this.popListenner();
    }

    componentWillUnmount() {
        this.props.formatVerifyTelephone(); // 手机号格式化
    }

    popListenner = () => {
        // 监听回退事件 回退关闭组件
        const closeListenner = () => {
            // WPT.initHtml(this.html);
            this.setState({ action: 'leave' });
            this.props.setShowCountrycodeList(false); // 调用父组件方法关闭子组件
            window.removeEventListener('popstate', closeListenner);
        };
        window.addEventListener('popstate', closeListenner);
        WPT.pushState(WPT.curUrl);
    };

    letterGroup = [
        '#',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
    ];

    renderCountriesByFirstLetter = () => (
        // 输入框为空时默认渲染完整列表
        <div className={styles.countries}>
            {Object.keys(fangg).map(letter => (
                <div className={styles.letterGroup} key={letter} id={`${letter}`}>
                    {letter !== '#' && <div className={styles.letter}>{letter}</div>}
                    {fangg[letter].map(i => (
                        <div
                            className={styles.countryItems}
                            key={i.code}
                            onClick={this.selectCountry(i.abbreviation, i.code, i.pattern, i.country)}
                        >
                            <span className={styles.countryName}>{i.country}</span>
                            <span className={styles.countryCode}>{`+${i.code}`}</span>
                        </div>
                    ))}
                </div>
            ))}
        </div>
    );

    renderCountriesByInputValue = () => {
        // 根据输入内容渲染列表
        const matchList = [];
        let matchFirstletter = false;
        // eslint-disable-next-line array-callback-return
        Object.keys(fangg).map(letter => {
            if (letter.toLowerCase() === this.state.inputValue.toLowerCase()) {
                fangg[letter].map(i => matchList.push(i));
                matchFirstletter = true;
            }
            fangg[letter].map(
                i => i.country.indexOf(this.state.inputValue) !== -1 && matchFirstletter === false && matchList.push(i)
            );
        });

        if (matchList.length === 0) {
            return (
                <div className={styles.countryItems}>
                    <span className={styles.noResult}>查询无结果</span>
                </div>
            );
        }
        return (
            <div className={styles.countries}>
                {matchList.map(i => (
                    <div
                        className={styles.countryItems}
                        key={i.code}
                        onClick={this.selectCountry(i.abbreviation, i.code, i.pattern, i.country)}
                    >
                        <span className={styles.countryName}>{i.country}</span>
                        <span className={styles.countryCode}>{`+${i.code}`}</span>
                    </div>
                ))}
            </div>
        );
    };

    anchorJump = letter => e => {
        // 跳转到对应区域
        e.preventDefault();
        const target = document.getElementById(`${letter}`);
        setTimeout(() => {
            target && target.scrollIntoView(true);
        }, 100);
    };

    moveSelect = e => {
        // 滑动索引跳转
        e.preventDefault();
        const a = document.elementFromPoint(e.touches[0].clientX, e.touches[0].clientY);
        if (a) {
            const target = document.getElementById(`${a.innerHTML}`);
            setTimeout(() => {
                target && target.scrollIntoView(true);
            }, 100);
        }
    };

    selectCountry = (abbreviation, code, pattern, country) => () => {
        // 选择国家后设置上一页面的状态并返回
        this.props.setCountryInfo(abbreviation, code, pattern, country);
        this.props.setShowCountrycodeList(false);
        if (this.props.noHistoryBack) return;
        // eslint-disable-next-line no-restricted-globals
        history.back();
    };

    valueChange = (clear = false) => e => {
        // 绑定input组件的onChange事件 // clear=true时清空搜索框内容
        this.setState({
            inputValue: !clear ? e.target.value : '',
        });
    };

    render() {
        const statusBarHeight = WPT.os.isFullscreen ? WPT.computedPosition(-44) : 0;
        const height = `calc(100vh - 1.32rem - ${statusBarHeight})`;

        return (
            <div
                className={cx(styles.container, styles[this.state.action])}
                style={{ paddingTop: statusBarHeight, background: '#f9f9f9' }}
            >
                <Search valueChange={this.valueChange} inputValue={this.state.inputValue} />
                <div className={styles.country}>
                    <div className={styles.scrollerHook} style={{ height }}>
                        {!this.state.inputValue
                            ? this.renderCountriesByFirstLetter()
                            : this.renderCountriesByInputValue()}
                    </div>
                    <div className={styles.shortcut}>
                        {this.letterGroup.map(letter => (
                            <div
                                className={styles.letters}
                                key={letter}
                                onTouchStart={this.anchorJump(letter)}
                                onTouchMove={this.moveSelect}
                                onClick={!$.os.phone ? this.anchorJump(letter) : () => {}}
                            >
                                {letter}
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        );
    }
}
